package ihs.markerUpdater;

import org.eclipse.core.resources.IMarker;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.Position;
import org.eclipse.ui.texteditor.IMarkerUpdater;
import org.eclipse.ui.texteditor.MarkerUtilities;

public class IHSMarkerUpdater implements IMarkerUpdater {

	private final static String[] ATTRIBUTES = { IMarker.CHAR_START,
			IMarker.CHAR_END, IMarker.LINE_NUMBER };

	@Override
	public String getMarkerType() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String[] getAttribute() {
		return ATTRIBUTES;
	}

	@Override
	public boolean updateMarker(IMarker marker, IDocument document,
			Position position) {
		if (position == null)
			return true;

		if (position.isDeleted())
			return false;

		boolean offsetsInitialized = false;
		boolean offsetsChanged = false;
		int markerStart = MarkerUtilities.getCharStart(marker);
		int markerEnd = MarkerUtilities.getCharEnd(marker);

		if (markerStart != -1 && markerEnd != -1) {

			offsetsInitialized = true;

			int offset = position.getOffset();
			if (markerStart != offset) {
				MarkerUtilities.setCharStart(marker, offset);
				offsetsChanged = true;
			}

			offset += position.getLength();
			if (markerEnd != offset) {
				MarkerUtilities.setCharEnd(marker, offset);
				offsetsChanged = true;
			}
		}

		if (!offsetsInitialized
				|| (offsetsChanged && MarkerUtilities.getLineNumber(marker) != -1)) {
			try {
				// marker line numbers are 1-based
				MarkerUtilities.setLineNumber(marker,
						document.getLineOfOffset(position.getOffset()) + 1);
			} catch (BadLocationException x) {
			}
		}

		return true;
	}

}
